package com.yam.michael.hibernate.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.xunjia.exception.XunjiaException;
import com.yam.michael.hibernate.dao.RightsDao;
import com.yam.michael.hibernate.pojo.Rights;

public class RightsDaoImpl extends HibernateDaoSupport implements RightsDao,Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2565722817675421791L;
	//日志
	public static final Logger logget = Logger.getLogger(RightsDaoImpl.class);

	@Override
	/**
	 * 添加用户权限
	 * @throws XunjiaException
	 */
	public Long addRights(Rights rights) throws XunjiaException {
		try {
		return (Long) this.getHibernateTemplate().save(rights);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("增加权限出错!!!");
		}
	}
	@Override
	/**
	 * 按ID获得用户权限
	 * @return
	 * @throws XunjiaException
	 */
	public void deleteRights(Rights rights) throws XunjiaException {
	    try {
			this.getHibernateTemplate().delete(rights);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("删除权限出错!!!");
		}
	}

	@Override
	/**
	 * 按ID获得用户权限
	 * @return
	 * @throws XunjiaException
	 */
	public Rights getRightsById(final String userId) throws XunjiaException {
		try {
			return (Rights) this.getHibernateTemplate().execute(new HibernateCallback(){

				@Override
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					Query q = session.createQuery("FROM Rights AS r WHERE r.userId=?");
					q.setString(0, userId);
					return q.uniqueResult();
				}});
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("通过ID获取权限出错,获取失败!!!");
		}
	}

	@Override
	/**
	 * 更新用户权限
	 * @throws XunjiaException
	 */
	public void updateRights(Rights rights) throws XunjiaException {
		try {
			this.getHibernateTemplate().saveOrUpdate(rights);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("修改权限出错,修改失败!!!");
		}
		
	}

}
